package com.reyco1.medusa.remoting.peer2peer
{
	import flash.events.NetStatusEvent;
	import flash.net.NetConnection;
	import flash.net.NetStream;
	import flash.net.sendToURL;

	public class PeerConnectionManager
	{
		private var nc:NetConnection;
		private var myPeerID:String;
		private var farPeerID:String;
		
		public var sendStream:NetStream;
		public var receiveStream:NetStream;
		
		public var receivedData:*;
		
		public function PeerConnectionManager()
		{
		}
		
		public function initialize():void
		{
			nc = new NetConnection();
			nc.addEventListener(NetStatusEvent.NET_STATUS, ncStatus);
			nc.connect(P2PData.RTMFP_GATEWAY + P2PData.DEVELOPER_KEY);
		}
		
		public function initSendStream():void
		{
			sendStream = new NetStream(nc, NetStream.DIRECT_CONNECTIONS);
			sendStream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
			sendStream.publish("media");
			
			var sendStreamClient:Object = {};
			sendStreamClient.onPeerConnect = function(callerNS:NetStream):Boolean
			{
				farPeerID = callerNS.farID;
				if(!receiveStream) initReceiveStream();
				return true;
			}
				
			sendStream.client = sendStreamClient;
		}
		
		public function initReceiveStream():void
		{
			receiveStream = new NetStream(nc, farPeerID);
			receiveStream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
			receiveStream.play("media");
			
			receiveStream.client = this;
		}
		
		public function receiveData(data:*):void
		{
			receivedData = data;
		}
		
		public function sendData(data:*):void
		{
			sendStream.send("receiveData", data);
		}
		
		/* handlers */
		
		private function ncStatus(e:NetStatusEvent):void
		{
			myPeerID = nc.nearID;
			initSendStream();
		}
		
		private function netStatusHandler(e:NetStatusEvent):void
		{
			
		}
	}
}